package team.stride;

import team.stride.database.crud.BDActivity;
import team.stride.gmap.Map;
import team.stride.tabs.HomeGroupActivity;
import team.stride.tabs.RecordsGroupActivity;
import team.stride.tabs.SettingsGroupActivity;
import team.stride.utils.UtilsStride;
import twitter4j.TwitterException;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.TabActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TabHost;

import com.facebook.android.BaseDialogListener;
import com.facebook.android.BaseRequestListener;

public class Stride extends TabActivity
{
	private static final int NOT_CONNECTED = 0;
	private static final int TWITTER_POST = 1;
	private static final int FACEBOOK_POST = 2;
	private TabHost tabHost;
	private Dialog twitterDialog;
	private Dialog facebookDialog;
	private AlertDialog notConnectedDialog;

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		initUtils();

		// Resources res = getResources(); // Resource object to get Drawables
		final String home = getString(R.string.home_tab);
		final String records = getString(R.string.records_tab);
		final String settings = getString(R.string.settings_tab);
		final Resources res = getResources();

		tabHost = getTabHost();

		tabHost.addTab(tabHost.newTabSpec(home).setIndicator(home, res.getDrawable(R.drawable.ic_tab_home)).setContent(
				new Intent(this, HomeGroupActivity.class)));

		tabHost.addTab(tabHost.newTabSpec(records).setIndicator(records, res.getDrawable(R.drawable.ic_tab_tracks))
				.setContent(new Intent(this, RecordsGroupActivity.class)));

		tabHost.addTab(tabHost.newTabSpec(settings).setIndicator(settings, res.getDrawable(R.drawable.ic_tab_settings))
				.setContent(new Intent(this, SettingsGroupActivity.class)));

		tabHost.setCurrentTab(0);
	}

	private void initUtils()
	{
		UtilsStride.mainActivity = this;
		UtilsStride.preferences = PreferenceManager.getDefaultSharedPreferences(this);

		initDialogs();
		startConnections();
	}

	private void startConnections()
	{
		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		if (cm.getActiveNetworkInfo() != null)
		{
			UtilsStride.rememberLastFacebookConnection();
			UtilsStride.rememberLastTwitterConnection();
		}
	}

	private void initDialogs()
	{
		// twitter
		twitterDialog = new Dialog(this);
		twitterDialog.setContentView(R.layout.twitter_post);
		twitterDialog.setTitle(R.string.twitter_post_title);
		twitterDialog.setCancelable(true);
		twitterDialog.setCanceledOnTouchOutside(true);

		Button postBtn = (Button) twitterDialog.findViewById(R.id.twitter_post_btn);
		Button cancelBtn = (Button) twitterDialog.findViewById(R.id.twitter_cancel_btn);
		final EditText message = (EditText) twitterDialog.findViewById(R.id.twitter_message);

		postBtn.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				try
				{
					UtilsStride.twitter.updateStatus(message.getText().toString());
					twitterDialog.dismiss();
				}
				catch (TwitterException e)
				{
					e.printStackTrace();
				}
			}
		});
		cancelBtn.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				twitterDialog.dismiss();
			}
		});

		// facebook
		facebookDialog = new Dialog(this);
		facebookDialog.setContentView(R.layout.facebook_post);
		facebookDialog.setTitle(R.string.facebook_post_title);
		facebookDialog.setCancelable(true);
		facebookDialog.setCanceledOnTouchOutside(true);

		Button postBtnF = (Button) facebookDialog.findViewById(R.id.facebook_post_btn);
		Button cancelBtnF = (Button) facebookDialog.findViewById(R.id.facebook_cancel_btn);

		postBtnF.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				UtilsStride.mFacebook.dialog(v.getContext(), "feed", new SampleDialogListener());
				facebookDialog.dismiss();
			}
		});
		cancelBtnF.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				facebookDialog.dismiss();
			}
		});

		// not connected
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(R.string.not_conn).setMessage(R.string.click_ok_conn).setCancelable(true).setPositiveButton(
				R.string.ok, new DialogInterface.OnClickListener()
				{
					public void onClick(DialogInterface dialog, int id)
					{
						tabHost.setCurrentTab(2);
						dialog.cancel();
					}
				}).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener()
		{
			public void onClick(DialogInterface dialog, int id)
			{
				dialog.cancel();
			}
		});
		notConnectedDialog = builder.create();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.running, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		// Handle item selection
		switch (item.getItemId())
		{
		case R.id.map:
			startActivity(new Intent(this, Map.class));
			return true;
		case R.id.post_f:
			boolean isConnF = false;
			synchronized (UtilsStride.isFacebookConnected)
			{
				isConnF = UtilsStride.isFacebookConnected;
			}
			if (isConnF)
			{
				showDialog(FACEBOOK_POST);
			}
			else
			{
				showDialog(NOT_CONNECTED);
			}
			return true;
		case R.id.post_t:
			boolean isConnT = false;
			synchronized (UtilsStride.isTwitterConnected)
			{
				isConnT = UtilsStride.isTwitterConnected;
			}
			if (isConnT)
			{
				showDialog(TWITTER_POST);
			}
			else
			{
				showDialog(NOT_CONNECTED);
			}
			return true;
		case R.id.db:
			startActivity(new Intent(this, BDActivity.class));
			return true;
		case R.id.exit:
			try
			{
				UtilsStride.mp.stop();
				UtilsStride.mp.release();
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
			finish();
			return true;
		default:
			return false;

		}
	}

	@Override
	protected Dialog onCreateDialog(int id)
	{
		switch (id)
		{
		case NOT_CONNECTED:
		{
			return notConnectedDialog;
		}
		case TWITTER_POST:

			return twitterDialog;
		case FACEBOOK_POST:

			return facebookDialog;
		}
		return null;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		UtilsStride.mFacebook.authorizeCallback(requestCode, resultCode, data);
	}

	public class SampleDialogListener extends BaseDialogListener
	{
		public void onComplete(Bundle values)
		{
			final String postId = values.getString("post_id");
			if (postId != null)
			{
				UtilsStride.mAsyncRunner.request(postId, new WallPostRequestListener());
			}
		}
	}

	public class WallPostRequestListener extends BaseRequestListener
	{
		public void onComplete(final String response)
		{
		}
	}
}